package com.imut.controller;

import com.imut.entity.NovelCategory;
import com.imut.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/novel/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public ResponseEntity<Boolean> insertCategory(@RequestBody NovelCategory novelCategory) {
        boolean result = categoryService.insertCategory(novelCategory);
        return result ? new ResponseEntity<>(true, HttpStatus.OK) :
                new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @PutMapping
    public ResponseEntity<Boolean> updateCategory(@RequestBody NovelCategory novelCategory) {
        boolean result = categoryService.updateCategory(novelCategory);
        return result ? new ResponseEntity<>(true, HttpStatus.OK) :
                new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Boolean> deleteCategory(@PathVariable Integer id) {
        boolean result = categoryService.deleteCategory(id);
        return result ? new ResponseEntity<>(true, HttpStatus.OK) :
                new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @GetMapping("/{id}")
    public ResponseEntity<NovelCategory> selectAllCategories(@PathVariable Integer id) {
        NovelCategory category = categoryService.selectAllCategories(id);
        return category != null ? new ResponseEntity<>(category, HttpStatus.OK) :
                new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @GetMapping
    public ResponseEntity<List<NovelCategory>> selectCategoryById() {
        List<NovelCategory> categories = categoryService.selectCategoryById();

        for (NovelCategory category : categories) {
            System.out.println(category);
        }

        return categories != null && !categories.isEmpty() ? new ResponseEntity<>(categories, HttpStatus.OK) :
                new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @GetMapping("/tree/{parentId}")
    public ResponseEntity<List<NovelCategory>> selectCategoriesWithChildren(@PathVariable Integer parentId) {
        List<NovelCategory> categories = categoryService.selectCategoriesWithChildren(parentId);
        return categories != null && !categories.isEmpty() ? new ResponseEntity<>(categories, HttpStatus.OK) :
                new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}
